package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.po.UserSettings;
import com.it.schoolbookshop_back.entities.dto.UserSettingsDTO;
import com.it.schoolbookshop_back.mapper.UserMapper;
import com.it.schoolbookshop_back.mapper.UserSettingsMapper;
import com.it.schoolbookshop_back.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserSettingsMapper userSettingsMapper;

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsernameAndPassword(username, password);
        
        // 如果登录成功，更新最后登录时间
        if (user != null) {
            try {
                userMapper.updateLastLoginTime(user.getId());
                log.info("用户 {} (ID: {}) 登录成功，已更新最后登录时间", username, user.getId());
            } catch (Exception e) {
                log.error("更新用户 {} (ID: {}) 最后登录时间失败: {}", username, user.getId(), e.getMessage(), e);
                // 登录时间更新失败不影响登录流程
            }
        }
        
        return user;
    }

    @Override
    public Integer register(User user) {
        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            return null;
        }
        
        // 插入用户
        int result = userMapper.insert(user);
        
        if (result > 0) {
            try {
                // 创建默认用户设置
                UserSettings userSettings = new UserSettings();
                userSettings.setUserId(user.getId());
                userSettings.setNotificationMessages(true);
                userSettings.setNotificationFavorites(true);
                userSettings.setNotificationTransactions(true);
                
                // 保存用户设置
                userSettingsMapper.insert(userSettings);
                log.info("已为新用户 {} (ID: {}) 创建默认设置", user.getUsername(), user.getId());
            } catch (Exception e) {
                log.error("为新用户 {} (ID: {}) 创建设置失败: {}", user.getUsername(), user.getId(), e.getMessage(), e);
                // 设置创建失败不影响注册流程
            }
            
            return user.getId();
        }
        
        return null;
    }

    @Override
    public User getUserById(Integer id) {
        User user = userMapper.findById(id);
        if (user != null) {
            // 添加数据库查询调试
            try {
                User freshUser = userMapper.findById(id);
                // 打印原始结果集
                System.out.println("===== 重新查询用户信息 =====");
                System.out.println("学号字段值: " + freshUser.getStudentId());
                System.out.println("实名字段值: " + freshUser.getRealName());
                System.out.println("===========================");
            } catch (Exception e) {
                System.out.println("调试查询异常: " + e.getMessage());
                e.printStackTrace();
            }
            
            System.out.println("=============================");
        }
        return user;
    }

    @Override
    public boolean isUsernameExists(String username) {
        User user = userMapper.findByUsername(username);
        return user != null;
    }
    
    @Override
    public boolean updateUser(User user) {
        // 不允许修改用户名和密码
        if (user.getId() == null) {
            return false;
        }
        
        // 执行更新
        int result = userMapper.updateUser(user);
        return result > 0;
    }

    @Override
    public boolean updateUserAvatar(Integer userId, byte[] avatarData, String avatarType) {
        try {
            // 检查用户是否存在
            User user = userMapper.getUserById(userId);
            if (user == null) {
                log.warn("用户不存在, ID: {}", userId);
                return false;
            }
            
            // 更新用户头像
            user.setAvatar(avatarData);
            user.setAvatarType(avatarType);
            
            // 保存更新
            int result = userMapper.updateUser(user);
            boolean success = result > 0;
            
            if (success) {
                log.info("用户头像更新成功, ID: {}", userId);
            } else {
                log.warn("用户头像更新失败, ID: {}", userId);
            }
            
            return success;
        } catch (Exception e) {
            log.error("更新用户头像失败, ID: {}, 错误: {}", userId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean verifyPassword(Integer userId, String password) {
        try {
            // 获取用户信息
            User user = userMapper.getUserById(userId);
            if (user == null) {
                log.warn("用户不存在, ID: {}", userId);
                return false;
            }
            
            // 验证密码
            return password.equals(user.getPassword());
        } catch (Exception e) {
            log.error("验证密码失败, 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean updatePassword(Integer userId, String newPassword) {
        try {
            // 获取用户信息
            User user = userMapper.getUserById(userId);
            if (user == null) {
                log.warn("用户不存在, ID: {}", userId);
                return false;
            }
            
            // 更新密码
            user.setPassword(newPassword);
            
            // 保存更新
            int result = userMapper.updateUser(user);
            boolean success = result > 0;
            
            if (success) {
                log.info("密码更新成功, 用户ID: {}", userId);
            } else {
                log.warn("密码更新失败, 用户ID: {}", userId);
            }
            
            return success;
        } catch (Exception e) {
            log.error("更新密码失败, 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public UserSettingsDTO getUserSettings(Integer userId) {
        try {
            // 检查用户是否存在
            User user = userMapper.getUserById(userId);
            if (user == null) {
                log.warn("获取用户设置失败：用户不存在, ID: {}", userId);
                return null;
            }
            
            // 获取用户设置
            UserSettings userSettings = userSettingsMapper.getByUserId(userId);
            
            // 如果用户设置不存在，创建默认设置
            if (userSettings == null) {
                userSettings = new UserSettings();
                userSettings.setUserId(userId);
                userSettings.setNotificationMessages(true);
                userSettings.setNotificationFavorites(true);
                userSettings.setNotificationTransactions(true);
                
                // 保存默认设置
                userSettingsMapper.insert(userSettings);
                log.info("为用户 {} 创建默认设置", userId);
            }
            
            // 将实体转换为DTO
            UserSettingsDTO dto = new UserSettingsDTO();
            dto.setNotificationMessages(userSettings.getNotificationMessages());
            dto.setNotificationFavorites(userSettings.getNotificationFavorites());
            dto.setNotificationTransactions(userSettings.getNotificationTransactions());
            
            log.info("成功获取用户 {} 的设置", userId);
            return dto;
        } catch (Exception e) {
            log.error("获取用户 {} 设置失败: {}", userId, e.getMessage(), e);
            
            // 发生错误时返回默认设置
            UserSettingsDTO defaultSettings = new UserSettingsDTO();
            defaultSettings.setNotificationMessages(true);
            defaultSettings.setNotificationFavorites(true);
            defaultSettings.setNotificationTransactions(true);
            return defaultSettings;
        }
    }
    
    /**
     * 更新用户设置
     *
     * @param userId  用户ID
     * @param settings 设置信息
     * @return 是否成功
     */
    @Override
    public boolean updateUserSettings(Integer userId, UserSettingsDTO settings) {
        try {
            // 获取当前设置
            UserSettings currentSettings = userSettingsMapper.getByUserId(userId);
            
            // 如果没有设置记录，则创建新记录
            if (currentSettings == null) {
                currentSettings = new UserSettings();
                currentSettings.setUserId(userId);
                
                // 设置默认值
                currentSettings.setNotificationMessages(true);
                currentSettings.setNotificationFavorites(true);
                currentSettings.setNotificationTransactions(true);
                
                // 设置需要更新的值
                if (settings.getNotificationMessages() != null) {
                    currentSettings.setNotificationMessages(settings.getNotificationMessages());
                }
                if (settings.getNotificationFavorites() != null) {
                    currentSettings.setNotificationFavorites(settings.getNotificationFavorites());
                }
                if (settings.getNotificationTransactions() != null) {
                    currentSettings.setNotificationTransactions(settings.getNotificationTransactions());
                }
                
                // 插入新记录
                int rows = userSettingsMapper.insert(currentSettings);
                if (rows <= 0) {
                    log.error("创建用户 {} 设置失败", userId);
                    return false;
                }
            } else {
                // 更新需要修改的字段
                boolean hasChanges = false;
                
                if (settings.getNotificationMessages() != null && 
                    !settings.getNotificationMessages().equals(currentSettings.getNotificationMessages())) {
                    currentSettings.setNotificationMessages(settings.getNotificationMessages());
                    hasChanges = true;
                }
                
                if (settings.getNotificationFavorites() != null && 
                    !settings.getNotificationFavorites().equals(currentSettings.getNotificationFavorites())) {
                    currentSettings.setNotificationFavorites(settings.getNotificationFavorites());
                    hasChanges = true;
                }
                
                if (settings.getNotificationTransactions() != null && 
                    !settings.getNotificationTransactions().equals(currentSettings.getNotificationTransactions())) {
                    currentSettings.setNotificationTransactions(settings.getNotificationTransactions());
                    hasChanges = true;
                }
                
                // 如果有修改，则更新数据库
                if (hasChanges) {
                    int rows = userSettingsMapper.update(currentSettings);
                    if (rows <= 0) {
                        log.error("更新用户 {} 设置失败", userId);
                        return false;
                    }
                }
            }
            
            return true;
        } catch (Exception e) {
            log.error("更新用户 {} 设置失败: {}", userId, e.getMessage(), e);
            return false;
        }
    }
} 